package com.xxx.springboot.distributedsession;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import com.xxx.springboot.util.Base64Utils;
import com.xxx.springboot.util.RedisUtil;


/**
 * 分布式session缓存引擎实现（基于redis）
 */
@Log4j2
public class RedisSessionCacheEngine implements SessionCacheEngine {
	
    @Override
    public boolean containsKey(String key) {
        return RedisUtil.hasKey(key);
    }

    @Override
    public Object get(String key) {
        log.debug("getSessionAttributeFromRedis|{}", key);
        try {
            String value = RedisUtil.get(key);
            if (StringUtils.isEmpty(value)) {
                return null;
            }
            return Base64Utils.base64ToObject(value);
        } catch (Exception e) {
            log.error("getSessionFromRedisError", e);
        }
        return null;
    }

    @Override
    public void remove(String key) {
        log.debug("removeSessionFromRedis|{}", key);
        RedisUtil.delete(key);
    }

    @Override
    public boolean put(String key, Object value, long expire) {
        log.debug("putSessionAttribute|{}", key);
        try {
            RedisUtil.set(key, Base64Utils.toBase64String(value), expire);
            return true;
        } catch (Exception e) {
            log.error("putSessionToRedisError", e);
        }
        return false;
    }

    @Override
    public void resetExpire(String key, long expire) {
        log.debug("resetSessionExpire|{}", key);
        RedisUtil.setExpiredTime(key, expire);
    }
}
